import { createRouter, createWebHashHistory, createWebHistory, ErrorHandler } from 'vue-router'
import store from '@/store'
import Layout from '@/views/index.vue'
const whiteList = ['/login']// no redirect whitelist
// 两种路由mode，hash和history
// const routerHistory = createWebHistory(process.env.BASE_URL); // createWebHistory()
const routerHistory = createWebHashHistory(process.env.BASE_URL) // createWebHistory()
export const constantRouterMap = [
  {
    path: '/',
    name: 'index',
    redirect: '/dashboard',
    component: Layout,
    children: [{
      path: '/dashboard',
      name: 'dashboard',
      // 单个router-view用：component
      component: () => import('../views/dashboard.vue'),
      hidden: true
    }, {
      path: '/baidumap',
      name: 'baidumap',
      // 单个router-view用：component
      component: () => import('../views/baidumap.vue'),
      hidden: true
    }],
    hidden: true
  }, {
    path: '/big_screen_main',
    name: 'big_screen_main',
    component: () => import('../views/big_screen_main.vue'),
    hidden: true
  }, {
    path: '/big_screen_main1',
    name: 'big_screen_main1',
    component: () => import('../views/big_screen_main1.vue'),
    hidden: true
  }, {
    path: '/login',
    name: 'login',
    component: () => import('../views/login.vue'),
    hidden: true
  }, {
    path: '/404',
    component: (resolve) => require(['@/views/features/404'], resolve),
    hidden: true
  },
  {
    path: '/401',
    component: (resolve) => require(['@/views/features/401'], resolve),
    hidden: true
  }
]
const router = createRouter({
  history: routerHistory,
  routes: constantRouterMap
})
router.beforeEach((to, from, next) => {
  console.log('router.beforeEach', to, from, next)
  if (store.state.user.token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => { // 拉取user_info
          // 动态路由，拉取菜单
          loadMenus(next, to)
        }).catch(() => {
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
        // 登录时未拉取 菜单，在此处拉取
      } else if (!store.getters.loadMenus) {
        loadMenus(next, to)
      } else {
        next()
      }
    }
  } else {
    /* 没有token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      if (to.fullPath === '/') {
        next(`/login`) // 否则全部重定向到登录页
      } else {
        next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      }
    }
  }

  // checkAuth(guard, router);
})
router.onError((handler) => {
  console.log('router.Error:', handler)
})
export const loadMenus = (next, to) => {
  store.dispatch('GetMenus').then(res => {
    const asyncRouter = filterAsyncRouter(res)
    asyncRouter.push({ path: '*', redirect: '/404', hidden: true })
    console.log(asyncRouter)
    console.log(router.getRoutes())
    addRoutes(asyncRouter, router) // 动态添加可访问路由表
    console.log(router)
    console.log(router.getRoutes())
    store.dispatch('updateRouters', buildRouterPath(asyncRouter))
    next({ ...to, replace: true })
  }).catch((error) => {
    console.log("store.dispatch('GetMenus') error", error)
    /* store.dispatch('LogOut').then(() => {
      location.reload() // 为了重新实例化vue-router对象 避免bug
    })*/
  })
}
export const filterAsyncRouter = (routers) => { // 遍历后台传来的路由字符串，转换为组件对象
  return routers.filter(router => {
    if (router.component) {
      if (router.component === 'Layout') { // Layout组件特殊处理
        // router.component = Layout
        if (router.path.toLowerCase().indexOf('http:') > -1 || router.path.toLowerCase().indexOf('https:') > -1) {
          // router.component = router.component
          router.component = null
        } else {
          router.component = Layout
        }
      } else {
        const component = router.component
        router.component = loadView(component)
      }
    }
    if (router.children && router.children.length) {
      router.children = filterAsyncRouter(router.children)
    }
    return true
  })
}
export const buildRouterPath = (routers, pPath) => { // 遍历后台传来的路由字符串，转换path
  return routers.filter(router => {
    if (router.path && pPath) {
      router.path = pPath + '/' + router.path
    }
    if (router.children && router.children.length) {
      router.children = buildRouterPath(router.children, router.path)
    }
    return true
  })
}
export const addRoutes = (asyncRouter, router) => { // 遍历后台传来的路由字符串，转换为组件对象
  asyncRouter.forEach(_router => {
    if (_router.component) {
      router.addRoute(_router)
      // router.addRoute(‘index’, _router)
      // router.options.routes[0].children.push(_router)
    }
    /* if (_router.children && _router.children.length) {
      _router.children = addRoutes(_router.children,router)
    }*/
  })
}
export const loadView = (view) => {
  // return (resolve) => require([`@/views/${view}`], resolve)
  return () => import('@/views/' + view)
}
export default router
